package com.sys.basics.service.impl;

import com.sys.basics.entity.SysResource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import com.sys.basics.entity.SysResource;
import com.sys.basics.dao.SysResourceDao;
import com.sys.basics.service.SysResourceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;


/**
 * @author: ares
 * @date: 2021-10-08
 * @description: 系统资源表 服务实现类
 */
@Slf4j
@Service
public class SysResourceServiceImpl extends ServiceImpl<SysResourceDao, SysResource> implements SysResourceService {
    @Autowired
	SysResourceDao sysResourceDao;
    public SysResource getTreeById(Long id) {
        return sysResourceDao.getTreeById(id);
    }

    @Override
    public List<SysResource> getChildrenTreeByParentId(Long parentId) {
        return sysResourceDao.getChildrenTreeByParentId(parentId);
    }

    @Override
    public List<SysResource> getChildrenByParentId(Long parentId) {
        return sysResourceDao.getChildrenByParentId(parentId);
    }

    /**
     * @param id
     * @return
     * @author: ares
     * @date: 2021/9/30 21:06
     * @description: 根据子节点ID查询上级tree
     */
    @Override
    public SysResource getTreeByIdAsLeaf(Long id) {
        return getParent(sysResourceDao.selectById(id));
    }


    /**
     * @param children
     * @return
     * @author: ares
     * @date: 2021/9/30 22:10
     * @description: 根据子节点查询父节点
     */
    private SysResource getParent(SysResource children) {
        if(children == null) return null;
        Long parentId = children.getParentId();
        if (parentId == 0) {
            return children;
        } else {
            SysResource parent = sysResourceDao.selectById(parentId);
            parent.setChildren(Arrays.asList(children));
            return getParent(parent);
        }
    }

    /**
     * @author: ares
     * @date: 2021/10/1 21:10
     * @description: 根据id删除自身及子节点
     * @param id
     * @return
     */
    @Override
    public boolean removeSelfAndChildrenById(Long id) {
        List<SysResource> children = sysResourceDao.getChildrenByParentId(id);
        if (children.size() > 0) {
            children.forEach(child -> removeSelfAndChildrenById(child.getId()));
        }
        return super.removeById(id);
    }

    @Override
    public List<SysResource> getParentTree() {
        return sysResourceDao.getParentTree((long) 0);
    }

    @Override
    public List<SysResource> getListByRoleId(Long roleId) {
        return sysResourceDao.getListByRoleId(roleId);
    }

    @Override
    public List<SysResource> getTreeByOrgId(Long orgId) {
        return sysResourceDao.getTreeByOrgId(orgId);
    }

}
